﻿using Fluffy.Library.Utils;
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Interactivity;
using System.Xml.Linq;

namespace Fluffy.Library.Behaviors
{
	public class RememberWindowPlacementBehavior : Behavior<Window>
    {
		private string FilePath
		{
			get { return Path.Combine(PathUtils.AppDataPath, AssociatedObject.GetType().Name + ".placement.xml"); }
		}

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.Initialized += OnInitialized;
			AssociatedObject.Closing += OnClosing;
        }

		private void OnClosing(object sender, CancelEventArgs e)
		{
			XDocument document = new XDocument();
			document.Add(new XElement("Placement"));

			document.Root.Add(new XElement("Left", AssociatedObject.RestoreBounds.Left.ToString(CultureInfo.InvariantCulture)));
			document.Root.Add(new XElement("Top", AssociatedObject.RestoreBounds.Top.ToString(CultureInfo.InvariantCulture)));
			document.Root.Add(new XElement("Width", AssociatedObject.RestoreBounds.Width.ToString(CultureInfo.InvariantCulture)));
			document.Root.Add(new XElement("Height", AssociatedObject.RestoreBounds.Height.ToString(CultureInfo.InvariantCulture)));
			document.Root.Add(new XElement("IsMaximized", (AssociatedObject.WindowState == WindowState.Maximized).ToString(CultureInfo.InvariantCulture)));

			string filePath = FilePath;
			string fileDir = Path.GetDirectoryName(filePath);

			if (!Directory.Exists(fileDir))
				Directory.CreateDirectory(fileDir);

			document.Save(FilePath);
		}

		private void OnInitialized(object sender, EventArgs e)
		{
			string filePath = FilePath;

			if (!File.Exists(filePath))
				return;

			XDocument document = XDocument.Load(filePath);
			AssociatedObject.WindowState = Boolean.Parse(document.Root.Element("IsMaximized").Value) ? WindowState.Maximized : WindowState.Normal;
			AssociatedObject.Left = Double.Parse(document.Root.Element("Left").Value, CultureInfo.InvariantCulture);
			AssociatedObject.Top = Double.Parse(document.Root.Element("Top").Value, CultureInfo.InvariantCulture);
			AssociatedObject.Width = Double.Parse(document.Root.Element("Width").Value, CultureInfo.InvariantCulture);
			AssociatedObject.Height = Double.Parse(document.Root.Element("Height").Value, CultureInfo.InvariantCulture);
		}
    }
}
